import useUserStore from '@/stores/user'
import { message } from 'ant-design-vue'
import axios, { AxiosRequestConfig } from 'axios'


export const _request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 60 * 1000,
})

// 请求拦截
_request.interceptors.request.use(value => {
  const { token } = useUserStore()
  if (token?.token) value.headers.Authorization = token.token
  return value
})

// 响应拦截
_request.interceptors.response.use(resp => {
  const res = resp.data as IResponse<any>
  if (res.code !== 1) {
    throw new Error(res.message || 'invalid response')
  }
  return resp
}, err => {
  message.error(err)
})

// 重构常用方法, 解包响应参数
export const request = {
  get: async function<T = IResponse<any>>(url: string, config?: AxiosRequestConfig) {
    return (await _request.get<T>(url, config)).data
  },
  post: async function<T = IResponse<any>>(url: string, data?: any, config?: AxiosRequestConfig) {
    return (await _request.post<T>(url, data, config)).data
  },
  delete: async function<T = IResponse<any>>(url: string, config?: AxiosRequestConfig) {
    return (await _request.delete<T>(url, config)).data
  },
  put: async function<T = IResponse<any>>(url: string, data?: any, config?: AxiosRequestConfig) {
    return (await _request.put<T>(url, data, config)).data
  },
  instance: _request
}

export default request
